import axios from 'axios'
import {MessageBox, Message, Loading} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'


let loading

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading() {
  loading.close()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0

export function showFullScreenLoading() {
  if ( needLoadingRequestCount === 0 ) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if ( needLoadingRequestCount <= 0 ) return
  needLoadingRequestCount--
  if ( needLoadingRequestCount === 0 ) {
    endLoading()
  }
}

const service = axios.create({
  baseURL: /*process.env.VUE_APP_BASE_API*/ 'http://8.136.115.59/api/', // url = base url + request url
  /*  withCredentials: true,*/ // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
    // do something before request is sent
    if ( store.getters.token ) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      /* config.headers['X-Token'] = getToken()*/
      if ( !config.headers.hasOwnProperty('token') ) {
        config.headers.token = store.getters.token;
        /*     config.headers.typename = store.getters.tokenValue;*/
      }
    }
    showFullScreenLoading()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    tryHideFullScreenLoading()
    const res = response.data
    if ( res.code !== 200 ) {
      tryHideFullScreenLoading()
      Message({
        message: res.msg || res.message,
        type: 'error',
        duration: 3 * 1000
      })

      // 401:未登录;
      if ( res.code === 401 ) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    tryHideFullScreenLoading()
    console.log('err' + error)// for debug
    if ( error.response.data.code == 500 ) {
      Message({
        message: "用户名或密码错误",
        type: 'error',
        duration: 3 * 1000
      })
    } else {
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
